package com.ll.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ll.common.utils.HttpUtils;
import com.ll.gulimall.member.dao.MemberLevelDao;
import com.ll.gulimall.member.entity.MemberLevelEntity;
import com.ll.gulimall.member.exception.CheckPhoneExistExecption;
import com.ll.gulimall.member.exception.CheckUserNameExistException;
import com.ll.gulimall.member.service.MemberLevelService;
import com.ll.gulimall.member.vo.UserLoginVo;
import com.ll.gulimall.member.vo.UserRegistVo;
import com.ll.gulimall.member.vo.WeiBoResVo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ll.common.utils.PageUtils;
import com.ll.common.utils.Query;

import com.ll.gulimall.member.dao.MemberDao;
import com.ll.gulimall.member.entity.MemberEntity;
import com.ll.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {


    @Autowired
    MemberLevelService memberLevelService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 注册会员
     *
     * @param vo
     */
    @Override
    public void regist(UserRegistVo vo) {
        //设置用户基本信息
        MemberEntity memberEntity = new MemberEntity();
        //会员默认等级
        MemberLevelEntity levelEntity = memberLevelService.selectDefaultLevel();
        memberEntity.setLevelId(levelEntity.getId());
        //密码  加密
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        //默认nikename
        memberEntity.setNickname(vo.getUsername());
        memberEntity.setPassword(passwordEncoder.encode(vo.getPassword()));
        //检查是否唯一 不唯一则抛出异常 username 让Controller 感知
        checkUserNameUnique(vo.getUsername());
        //检查是否唯一 不唯一则抛出异常 phone 让Controller 感知
        checkPhoneUnique(vo.getPhone());
        //手机号 是否唯一
        memberEntity.setMobile(vo.getPhone());
        //用户名 是否唯一
        memberEntity.setUsername(vo.getUsername());
        this.baseMapper.insert(memberEntity);
    }

    @Override
    public void checkUserNameUnique(String username) throws CheckUserNameExistException {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (count > 0) {
            //如果存在抛出异常
            throw new CheckUserNameExistException();
        }

    }

    @Override
    public void checkPhoneUnique(String phone) throws CheckPhoneExistExecption {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (count > 0) {
            //如果存在抛出异常
            throw new CheckPhoneExistExecption();
        }

    }

    @Override
    public MemberEntity login(UserLoginVo loginVo) {
        String loginacct = loginVo.getLoginacct();
        String password = loginVo.getPassword();
        //去数据库查询 select * from `ums_member` where username='xxx' or mobile='xxx'
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct).or().eq("mobile", loginacct));

        if (memberEntity != null) {
            //有这个用户 再来对比密码
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            if (passwordEncoder.matches(password, memberEntity.getPassword())) {
                //密码正确登陆成功
                return memberEntity;
            }
        }
        return null;
    }

    /**
     * 微博登录
     *
     * @param weiBoResVo
     * @return
     */
    @Override
    public MemberEntity login(WeiBoResVo weiBoResVo) throws Exception {
        String uid = weiBoResVo.getUid();
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("uid", uid));
        if (memberEntity != null) {
            //用户之前使用微博登录过 修改用户数据返回用户即可
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(weiBoResVo.getAccess_token());
            update.setRemindIn(Long.parseLong(weiBoResVo.getRemind_in()));
            this.baseMapper.updateById(update);
            //返回用户
            memberEntity.setRemindIn(Long.parseLong(weiBoResVo.getRemind_in()));
            memberEntity.setAccessToken(weiBoResVo.getAccess_token());
            return memberEntity;
        } else {
            //用户第一次使用微博登录
            MemberEntity loginEntity = new MemberEntity();
            //把微博用户关联到用户中 方便用户下次登录
            loginEntity.setCreateTime(new Date());
            loginEntity.setAccessToken(weiBoResVo.getAccess_token());
            loginEntity.setRemindIn(Long.parseLong(weiBoResVo.getRemind_in()));
            loginEntity.setUid(weiBoResVo.getUid());
            Map<String, String> map = new HashMap<>();
            map.put("access_token", weiBoResVo.getAccess_token());
            map.put("uid", weiBoResVo.getUid());
            try {
                //根据Access_token 查询用户信息
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<>(), map);
                if (response.getStatusLine().getStatusCode() == 200) {
                    //调用成功
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject object = JSON.parseObject(json);
                    loginEntity.setNickname(object.getString("screen_name"));
                    loginEntity.setGender(object.getString("gender").equals("m") ? 0 : 1);
                }

            } catch (Exception e) {

            }
            baseMapper.insert(loginEntity);

            return loginEntity;

        }


    }

}